package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.bean.VoiceBean;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyListView;
import com.xn.app.muying.view.RoundImageView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Request;

/**
 * 语音解答列表页面
 * Created by gaoge on 2017/8/11.
 */

public class VoiceSolutionListActivity extends BaseActivity implements View.OnClickListener, MyListView.IXListViewListener {

    //标题
    private TextView title_name = null;
    //返回键
    private ImageView img_back = null;
    //接收页面传来的数据
    private Intent intent = null;
    //需要查询的关键字
    private String data = "";
    //需要查询的分类
    private String type = "";
    //数据显示列表
    private MyListView listview = null;
    //空页面
    private LinearLayout no_data_linearlayout = null;
    //保存语音数据集合
    private ArrayList<VoiceBean> voiceSolutionList = new ArrayList<>();
    //适配器
    private MyAdpter myAdpter = null;
    //图片加载
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    //加载框
    AlertDialog dialog;
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 10;
    //判断是否可以听语音
    private int answerTimes = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载布局
        setContentView(R.layout.voice_solution_list_activity);
        //初始化
        init();
    }

    /**
     * 初始化布局
     */
    private void init() {
        //加载并缓存图片
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.home_doctor_moren) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.home_doctor_moren) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        //获取数据
        intent = getIntent();
        data = intent.getStringExtra("data");
        type = intent.getStringExtra("type");
        //初始化组件
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        listview = (MyListView) findViewById(R.id.listview);
        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        //设置listview适配器
        myAdpter = new MyAdpter(this, voiceSolutionList, imageLoader, options);
        listview.setAdapter(myAdpter);
        //设置标题
        title_name.setText("搜索结果");
        //点击事件
        img_back.setOnClickListener(this);
        //判断网络状态
        if (NetworkUtil.isNetworkAvailable(this)) {
            dialog = new MyAlertDialog().ShowDialog(this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            answerTimes = AppConstant.getAnswerTimes(VoiceSolutionListActivity.this);
            //下载数据
            downloadData();
        } else {
            no_data_linearlayout.setVisibility(View.VISIBLE);
        }

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                answerTimes = AppConstant.getAnswerTimes(VoiceSolutionListActivity.this);
                if (answerTimes > 0) {
                    Intent intent = new Intent(VoiceSolutionListActivity.this, VoiceSolutionDetailActivity.class);
                    intent.putExtra("id", voiceSolutionList.get(position).getId());
                    startActivity(intent);
                } else {
                    listview.setPullLoadEnable(true);
                    listview.setXListViewListener(VoiceSolutionListActivity.this, totalCount, currentPage, number);
                    myAdpter.getData(voiceSolutionList);
                    ToastUtil.showToast(VoiceSolutionListActivity.this, R.string.no_voice);
                }

            }
        });
    }

    /**
     * 下载数据
     */
    private void downloadData() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.HomeVoiceSolution(type, data, currentPage, number)).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    int code = response.code();
                    if (code == 200 || code == 204) {
                        onJsonData(bodys);
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                no_data_linearlayout.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 数据解析
     *
     * @param bodys 数据
     */
    private void onJsonData(String bodys) {
        try {
            //解析数据
            JSONObject jsonObject = new JSONObject(bodys);
            //获取数据总量
            if (totalCount == 0) {
                totalCount = Integer.parseInt(jsonObject.get("totalCount").toString());
            }
            JSONArray jsonArray = jsonObject.getJSONArray("items");
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObject = jsonArray.getJSONObject(i);
                int id = jsonObject.getInt("id");
                String title = jsonObject.getString("title");
                String lable = jsonObject.getString("lable");
                String author = jsonObject.getString("author");
                int price = jsonObject.getInt("price");
                int frequencyId = jsonObject.getInt("frequencyId");
                String reference = jsonObject.getString("reference");
                boolean isPresent = jsonObject.getBoolean("isPresent");
                String remainingTimes = jsonObject.getString("remainingTimes");
                int doctorId = jsonObject.getInt("doctorId");
                //获取语音信息
                JSONObject jsonObject1 = new JSONObject(jsonObject.getString("frequency"));
                String frequencyName = jsonObject1.getString("frequencyName");
                String frequencyUploadDate = jsonObject1.getString("frequencyUploadDate");
                String frequencyUrl = jsonObject1.getString("frequencyUrl");
                int playTime = jsonObject1.getInt("playTime");
                String playDate =jsonObject1.getString("playDate");
                //获取医生信息
                JSONObject jsonObject2 = new JSONObject(jsonObject.getString("doctor"));
                String name = jsonObject2.getString("name");
                String photoUrl = jsonObject2.getString("photoUrl");
                String professionalTitle = jsonObject2.getString("professionalTitle");
                String primaryDepartmentName = jsonObject2.getString("primaryDepartmentName");
                String primaryHospitalName = jsonObject2.getString("primaryHospitalName");
                String expertise = jsonObject2.getString("expertise");
                String expertise2 = jsonObject2.getString("expertise2");
                String expertise3 = jsonObject2.getString("expertise3");
                String expertiseInput = jsonObject2.getString("expertiseInput");
                boolean isDeleted = jsonObject2.getBoolean("isDeleted");
                String doctorInfoId = jsonObject2.getString("doctorInfoId");
                //封装数据
                VoiceBean voiceBean = new VoiceBean();
                voiceBean.setId(id);
                voiceBean.setTitle(title);
                voiceBean.setLable(lable);
                voiceBean.setAuthor(author);
                voiceBean.setPrice(price);
                voiceBean.setFrequencyId(frequencyId);
                voiceBean.setFrequencyName(frequencyName);
                voiceBean.setFrequencyUploadDate(frequencyUploadDate);
                voiceBean.setFrequencyUrl(frequencyUrl);
                voiceBean.setPlayDate(playDate);
                voiceBean.setPlayTime(playTime);
                voiceBean.setDoctorId(doctorId);
                voiceBean.setName(name);
                voiceBean.setPhotoUrl(photoUrl);
                voiceBean.setProfessionalTitle(professionalTitle);
                voiceBean.setPrimaryDepartmentName(primaryDepartmentName);
                voiceBean.setPrimaryHospitalName(primaryHospitalName);
                voiceBean.setExpertise(expertise);
                voiceBean.setExpertise2(expertise2);
                voiceBean.setExpertise3(expertise3);
                voiceBean.setExpertiseInput(expertiseInput);
                voiceBean.setDeleted(isDeleted);
                voiceBean.setDoctorInfoId(doctorInfoId);
                voiceBean.setReference(reference);
                voiceBean.setPresent(isPresent);
                voiceBean.setRemainingTimes(remainingTimes);
                voiceSolutionList.add(voiceBean);
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    if (voiceSolutionList.size() > 0) {
                        if (listview.getVisibility() == View.GONE) {
                            listview.setVisibility(View.VISIBLE);
                        }
                        listview.setPullLoadEnable(true);
                        listview.setXListViewListener(VoiceSolutionListActivity.this, totalCount, currentPage, number);
                        myAdpter.getData(voiceSolutionList);
                    } else {
                        no_data_linearlayout.setVisibility(View.VISIBLE);
                    }
                    onLoad();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 列表适配器
     */
    class MyAdpter extends BaseAdapter {
        LayoutInflater lf = null;
        ArrayList<VoiceBean> getData = new ArrayList<VoiceBean>();
        ViewHolder viewHolder = null;
        private ImageLoader imageLoader = null;
        private DisplayImageOptions options = null;

        public MyAdpter(Context context, ArrayList<VoiceBean> getData,
                        ImageLoader loader,
                        DisplayImageOptions options) {
            lf = LayoutInflater.from(context);
            this.imageLoader = loader;
            this.options = options;
            this.getData = getData;
        }

        @Override
        public int getCount() {
            return getData.size();
        }

        public void getData(ArrayList<VoiceBean> data) {
            this.getData = data;
            notifyDataSetChanged();
        }

        @Override
        public Object getItem(int position) {
            return getData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return getData.get(position).getId();
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = lf.inflate(R.layout.voice_item, null);
                viewHolder.img = (RoundImageView) convertView.findViewById(R.id.img);
                viewHolder.voice = (ImageView) convertView.findViewById(R.id.voice);
                viewHolder.wifi_loading = (View) convertView.findViewById(R.id.wifi_loading);
                viewHolder.xian1 = (View) convertView.findViewById(R.id.xian1);
                viewHolder.time = (TextView) convertView.findViewById(R.id.time);
                viewHolder.title = (TextView) convertView.findViewById(R.id.title);
                viewHolder.name = (TextView) convertView.findViewById(R.id.name);
                viewHolder.hospitalname = (TextView) convertView.findViewById(R.id.hospitalname);
                viewHolder.professionaltitle = (TextView) convertView.findViewById(R.id.professionaltitle);
                convertView.setTag(viewHolder);
            } else {
                viewHolder.wifi_loading = (View) convertView.findViewById(R.id.wifi_loading);
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.title.setText(getData.get(position).getTitle());
            viewHolder.name.setText(getData.get(position).getName());
            viewHolder.hospitalname.setText(getData.get(position).getPrimaryHospitalName());
            viewHolder.professionaltitle.setText(getData.get(position).getProfessionalTitle());
            if (getData.get(position).getProfessionalTitle() != null && getData.get(position).getProfessionalTitle().length() > 0) {
                viewHolder.xian1.setVisibility(View.VISIBLE);
            }
            imageLoader.displayImage(getData.get(position).getPhotoUrl(), viewHolder.img, options);
            int time=getData.get(position).getPlayTime()+5;
            viewHolder.time.setText(time/60+"分"+time%60+"秒");
//            if(getData.get(position).getPlayDate().length()>0){
//                viewHolder.time.setText(getData.get(position).getPlayDate().replace("′","分").replace("″","秒"));
//            }
            viewHolder.wifi_loading.setBackgroundResource(R.drawable.wifi5);
            if(answerTimes<=0){
                viewHolder.voice.setBackgroundResource(R.mipmap.voice_no_moren);
            }
            return convertView;
        }
    }

    /**
     * 包装类
     */
    public static class ViewHolder {
        public RoundImageView img = null;
        public ImageView voice = null;
        public View wifi_loading = null;
        public TextView time = null;
        public TextView title = null;
        public TextView name = null;
        public TextView hospitalname = null;
        public TextView professionaltitle = null;
        public View xian1 = null;


    }

    /**
     * 点击事件
     *
     * @param v 控件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回键
            case R.id.img_back:
                finish();
                break;
        }
    }

    //上拉加载更多
    @Override
    public void onLoadMore() {
        if (totalCount > currentPage * number) {
            currentPage = currentPage + 1;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(AppConstant.THREAD_SLEEP);
                        //下载数据
                        downloadData();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            onLoad();
        }
    }

    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        listview.stopLoadMore();
    }
}
